package com.dkm.nettysocketdemo.myWebsite.service.impl;

import com.dkm.nettysocketdemo.myWebsite.dao.HelmetLogMapper;
import com.dkm.nettysocketdemo.myWebsite.domain.HelmetLog;
import com.dkm.nettysocketdemo.myWebsite.service.HelmetLogService;
import com.dkm.nettysocketdemo.untils.redis.RedisOperator;
import com.google.gson.Gson;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName : HelmetLogServiceImpl  //类名
 * @Description : 安全帽日志实现类  //描述
 * @Author : 易嵘  //作者
 * @Date: 2021-03-19 11:19  //时间
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class HelmetLogServiceImpl implements HelmetLogService {

    @Resource
    HelmetLogMapper logMapper;

    @Resource
    RedisOperator redisOperator;

    Gson gson = new Gson();

    /**
     * 根据安全帽id查询所有日志
     * @param helmetId 安全帽id
     * @return 查询结果
     */
    @Override
    public List<HelmetLog> findHelmetId(String helmetId) {
        List<String> list = redisOperator.lGet(helmetId+"List",0,-1);
        List<HelmetLog> logs ;
        if(ObjectUtils.isEmpty(list)){
            logs = new LinkedList<>();
            for (String s : list) {
                logs.add(gson.fromJson(s,HelmetLog.class));
            }
        }else {
            logs = logMapper.findHelmetId(helmetId);
            for (HelmetLog log : logs) {
                redisOperator.lSet(helmetId+"List",gson.toJson(log));

            }
        }
        return logs;
    }

    /**
     * 新增日志
     * @param log 日志模型
     * @return 回调函数
     */
    @Override
    public int add(HelmetLog log) {
        log.setPkLogId(UUID.randomUUID().toString().replaceAll("-",""));
        log.setLogTime(new Date());
        int row = logMapper.insertSelective(log);
        if(row > 0 ){
            redisOperator.lSet(log.getHelmetId()+"List",gson.toJson(log));
        }
        return row;
    }
}
